package org.pub.app.lunch;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class SearchForm extends Activity {
	private Spinner depSpinner = null;
	private Spinner arrSpinner = null;
	private Button okButton = null;
	private TextView depDateText = null;
	private Calendar todayCal = Calendar.getInstance();
	private AlertDialog.Builder builder = null;
	private AlertDialog dialog = null;
	private TextView arrCityText = null;
	private EditText arrDateText = null;
	private Spinner adultCountSpinner = null;
	private Spinner childCountSpinner = null;
	private Spinner tripTypeSpinner = null;
	private Spinner favorSpinner = null;

	private int dateInt = 0;
	private String[][] depItem = { { "서울", "인천", "김포" }, { "SEL", "ICN", "GMP" } };
	private String[][] arrItem = { { "제주" }, { "CJU" } };
	private String[] countItem = { "0명", "1명", "2명" };
	private String[][] tripItem = { { "왕복", "편도" }, { "2", "1" } }; //RT OW
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

	DatePickerDialog.OnDateSetListener datePicker = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

			DecimalFormat dcf = new DecimalFormat("00");

			String dateStr = year + "/" + dcf.format(monthOfYear + 1) + "/" + dcf.format(dayOfMonth);
			if (dateInt == 0) {
				depDateText.setText(dateStr);
			} else {
				arrDateText.setText(dateStr);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.form);

		tripTypeSpinner = (Spinner) findViewById(R.id.tripType);
		depSpinner = (Spinner) findViewById(R.id.depCitySpinner);
		arrSpinner = (Spinner) findViewById(R.id.arrSpinner);
		okButton = (Button) findViewById(R.id.ok);
		depDateText = (TextView) findViewById(R.id.depDateText);
		arrCityText = (EditText) findViewById(R.id.arrCityText);
		arrDateText = (EditText) findViewById(R.id.arrDateText);
		adultCountSpinner = (Spinner) findViewById(R.id.adultCount);
		childCountSpinner = (Spinner) findViewById(R.id.childCount);
		favorSpinner = (Spinner) findViewById(R.id.favorSpinner);

		tripTypeSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, tripItem[0]));

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, depItem[0]);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		depSpinner.setAdapter(adapter);
		depSpinner.setSelection(2);

		todayCal.add(Calendar.DATE, 30);
		arrSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrItem[0]));
		depDateText.setText(sdf.format(todayCal.getTime()));
		depDateText.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				dateInt = 0;
				new DatePickerDialog(v.getContext(), datePicker, todayCal.get(Calendar.YEAR), todayCal.get(Calendar.MONDAY), todayCal.get(Calendar.DAY_OF_MONTH)).show();
			}

		});

		todayCal.add(Calendar.DATE, 2);
		arrDateText.setText(sdf.format(todayCal.getTime()));
		arrDateText.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				dateInt = 1;
				new DatePickerDialog(v.getContext(), datePicker, todayCal.get(Calendar.YEAR), todayCal.get(Calendar.MONDAY), todayCal.get(Calendar.DAY_OF_MONTH)).show();
			}
		});

		arrCityText.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				LayoutInflater inflater = (LayoutInflater) v.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout = inflater.inflate(R.layout.citydialog, (ViewGroup) findViewById(R.id.cityDialogLayout));

				builder = new AlertDialog.Builder(v.getContext());
				builder.setView(layout);
				dialog = builder.create();
				dialog.setTitle("도시선택");
				View customView = createCustomView();
				dialog.setView(customView);
				dialog.setButton("확인", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/*
						try {
							URL url = new URL("http://192.168.1.176:8080/CommonUtilXml.lts?mode=city&code=");
							XmlPullParserFactory xmlFactory = XmlPullParserFactory.newInstance();
							XmlPullParser parser = xmlFactory.newPullParser();

							parser.setInput(url.openStream(), null);

						} catch (Exception e) {

							e.printStackTrace();

						}
						*/
					}
				});

				dialog.show();

			}
		});

		adultCountSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countItem));
		adultCountSpinner.setSelection(1);

		childCountSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countItem));

		okButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				String tot_step = tripItem[1][tripTypeSpinner.getSelectedItemPosition()];
				String dep_city = depItem[1][depSpinner.getSelectedItemPosition()];
				String dep_date = depDateText.getText().toString().replaceAll("/", "");
				String arr_city = arrItem[1][arrSpinner.getSelectedItemPosition()];
				String arr_date = arrDateText.getText().toString().replaceAll("/", "");
				String adult = String.valueOf(adultCountSpinner.getSelectedItemPosition());
				String child = String.valueOf(childCountSpinner.getSelectedItemPosition());
				String favor = getResources().getStringArray(R.array.favorArrayValue)[favorSpinner.getSelectedItemPosition()];

				QueryData query = new QueryData();
				query.setTot_step(tot_step);
				query.setDep_city(dep_city);
				query.setDep_date(dep_date);
				query.setArr_city(arr_city);
				query.setArr_date(arr_date);
				query.setAdult(adult);
				query.setChild(child);
				query.setFavorCar(favor);

				Intent in = new Intent(getBaseContext(), AvailActivity.class);
				in.putExtra("query", query);

				startActivity(in);

			}
		});

	};

	ArrayList<String> items = new ArrayList<String>();
	ArrayList<String> apCodeList = new ArrayList<String>();

	private View createCustomView() {
		/*
				try {
					String tagName = "";

					URL url = new URL("http://192.168.1.176:8080/CommonUtilXml.lts?mode=city&code=");
					XmlPullParserFactory xmlFactory = XmlPullParserFactory.newInstance();
					XmlPullParser parser = xmlFactory.newPullParser();

					parser.setInput(url.openStream(), "euc-kr");

					for (int eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser.next()) {
						if (eventType == XmlPullParser.START_TAG) {
							tagName = parser.getName();
						} else if (eventType == XmlPullParser.TEXT) {
							if (tagName.equals("cty_ct_desc")) {
								items.add(parser.getText());
							}
							if (tagName.equals("cty_ap_code")) {
								apCodeList.add(parser.getText());
							}
						} else if (eventType == XmlPullParser.END_TAG) {
							tagName = "";
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
		*/
		Document xmlDoc = null;

		try {

			String xml = readXml();
			System.out.println(xml);
			/*
			  DocumentBuilderFactory docBF =
			  DocumentBuilderFactory.newInstance(); DocumentBuilder docB =
			  docBF.newDocumentBuilder(); InputStream is = new
			  ByteArrayInputStream(xml.getBytes("euc-kr")); Document doc =
			  docB.parse(is);
			 */

			xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("euc-kr")));

		} catch (Exception e) {
			e.printStackTrace();
		}

		Element root = xmlDoc.getDocumentElement();
		NodeList CityList = root.getElementsByTagName("CityList");

		for (int i = 0; i < CityList.getLength(); i++) {
			Element elm = (Element) CityList.item(i);
			items.add(elm.getElementsByTagName("cty_ap_code").item(0).getFirstChild().getNodeValue());

			Node node = CityList.item(i);
			System.out.println("2222 " + node.getChildNodes().item(0).getFirstChild().getNodeValue());
		}

		LinearLayout linearLayoutView = new LinearLayout(this);

		ListView listview = new ListView(this);
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrItem[0]);

		listview.setAdapter(aa);
		listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				arrCityText.setText(arrItem[1][position]);
			}
		});

		TextView tv = new TextView(this);
		tv.setText("  Custom View 영역");

		linearLayoutView.setOrientation(LinearLayout.VERTICAL);
		linearLayoutView.addView(tv);
		linearLayoutView.addView(listview);

		return linearLayoutView;
	}

	private String readXml() throws Exception {
		StringBuffer xml = new StringBuffer();
		String line = null;

		URL url = new URL("http://192.168.1.176:8080/CommonUtilXml.lts?mode=city&code=");
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "euc-kr"));
		while ((line = reader.readLine()) != null) {
			xml.append(line);
			// System.out.println(line);
		}

		return xml.toString();
	}

}
